//
//  GRAddressListViewController.m
//  YC_GRice
//
//  Created by luojinrong11 on 2018/7/9.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRAddressListViewController.h"
#import "GRAddressTableViewCell.h"
#import "GRReceiveAddressViewController.h"
#import "GRBlankSpace.h"
@interface GRAddressListViewController ()<UITableViewDataSource,UITableViewDelegate,GRAddressTableViewCellDelegate,GRBlankSpaceDelegate>

{
    NSIndexPath *defaultAddressIndex;
}
@property (strong, nonatomic) IBOutlet UIView *headerView;

@property (weak, nonatomic) IBOutlet UITableView *addressList;
@property(nonatomic,strong)NSMutableArray * addressArr;
@property(nonatomic,strong)GRBlankSpace *blankSpceView;

@end

@implementation GRAddressListViewController
-(GRBlankSpace *)blankSpceView{
    if (!_blankSpceView) {
        _blankSpceView = [GRBlankSpace xx_instantiateFromNib];
        _blankSpceView.contentMode =  GRBlankContentModeEmptyAddress;
        _blankSpceView.delegate = self;
        CGFloat top = IS_IPHONEX ?143:119;
        _blankSpceView.frame = CGRectMake(0, top, self.view.bounds.size.width, self.view.bounds.size.height-top);
        [self.view addSubview:_blankSpceView];
    }
    return _blankSpceView;
}

-(NSMutableArray *)addressArr {
    if (!_addressArr) {
        _addressArr = [NSMutableArray array];
    }
    return _addressArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.addressList.tableHeaderView = self.headerView;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.addressList registerNib:[UINib nibWithNibName:@"GRAddressTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"addressCell"];
    [self loadData];
}

-(void)loadData{
    [RequestManager getMyAddressList:^(BOOL success, id responseObject, GRError *error) {
        if (success) {
            if (Array(responseObject)) {
                [self.addressArr removeAllObjects];
                for (NSDictionary *addressDic in responseObject) {
                    GRMyAddressEditorModel * addressModel = [GRMyAddressEditorModel yy_modelWithDictionary:addressDic];
                    [self.addressArr addObject:addressModel];
                }
                self.blankSpceView.hidden = self.addressArr.count > 0?YES:NO;
                [self.addressList reloadData];
            }
        }else{
        }
    }];
}

- (IBAction)CreateNewAddrAction:(UIButton *)sender {
    [self pushToAddOrEditorAddressVC:NO AddressId:0 ];
    }

- (void)didClickBlankButton:(UIButton *)sender{
       [self pushToAddOrEditorAddressVC:NO AddressId:0 ];
    
}

-(void)pushToAddOrEditorAddressVC:(BOOL)editor AddressId:(NSInteger)addressId{
    GRReceiveAddressViewController *createAddressVC = [[GRReceiveAddressViewController alloc]init];
    createAddressVC.editor = editor;
    createAddressVC.addressId = addressId;
    WEAKSELF
    createAddressVC.createAddrFinish = ^{
        [weakSelf loadData];
    };
    [self.navigationController pushViewController:createAddressVC animated:YES];
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GRAddressTableViewCell * addressCell = [tableView dequeueReusableCellWithIdentifier:@"addressCell" forIndexPath:indexPath];
    GRMyAddressEditorModel * addressModel = self.addressArr[indexPath.row];
    addressCell.addressModel = addressModel;
    if (addressModel.isDefault) {
        defaultAddressIndex = indexPath;
    }
    addressCell.delegate = self;
    
    return addressCell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    GRMyAddressEditorModel * addressModel = self.addressArr[indexPath.row];
    return addressModel.addressCellHeight;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.addressArr.count;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_isSelected) {
        if (_delegate && [_delegate respondsToSelector:@selector(selectedAddressModel:)]) {
            [_delegate selectedAddressModel:self.addressArr[indexPath.row]];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}
#pragma mark -GRAddressTableViewCellDelegate
-(void)editorAddress:(GRAddressTableViewCell *)addressCell AddressModel:(GRMyAddressEditorModel *)addressModel{
    
    [self pushToAddOrEditorAddressVC:YES AddressId:addressModel.id];
}

-(void)deleteAddress:(GRAddressTableViewCell *)addressCell AddressModel:(GRMyAddressEditorModel *)addressModel{
    WEAKSELF
    [RequestManager deleteAddressWithAddressId:addressModel.id ComplectionHander:^(BOOL success, id responseObject, GRError *error) {
        if (success) {
            [GRHUD showMessage:@"删除成功"];
            NSIndexPath * deleteIndex = [self.addressList indexPathForCell:addressCell];
            if ([defaultAddressIndex isEqual:deleteIndex]) {
                defaultAddressIndex = nil;
            }
            [weakSelf.addressArr removeObjectAtIndex:deleteIndex.row];
             self.blankSpceView.hidden = weakSelf.addressArr.count > 0?YES:NO;
            [weakSelf.addressList deleteRowsAtIndexPaths:@[deleteIndex] withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
}

-(void)setDefaultAdrress:(GRAddressTableViewCell *)addressCell AddressModel:(GRMyAddressEditorModel *)addressModel{
    WEAKSELF
    [RequestManager setDefaultAddress:addressModel.id ComplectionHander:^(BOOL success, id responseObject, GRError *error) {
        if (success) {
            [GRHUD showMessage:@"设置默认地址成功"];
            addressModel.isDefault = YES;
            NSIndexPath * index =  [weakSelf.addressList indexPathForCell:addressCell];
         
            if (defaultAddressIndex) {
                GRMyAddressEditorModel * addressModel = self.addressArr[defaultAddressIndex.row];
                addressModel.isDefault = NO;
                [weakSelf.addressList reloadRowsAtIndexPaths:@[index,defaultAddressIndex] withRowAnimation:UITableViewRowAnimationNone];
            }else{
                [weakSelf.addressList reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];
            }
    
            defaultAddressIndex = index;
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
